package com.david.rabbitdlq.service;

import com.alibaba.fastjson.JSON;
import com.david.rabbitdlq.config.RabbitConfig;
import com.david.rabbitdlq.dao.OrderRepository;
import com.david.rabbitdlq.entity.Order;
import com.david.rabbitdlq.entity.OrderStatus;
import com.david.rabbitdlq.util.OrderHelper;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.time.Duration;
import java.util.Objects;

import static com.david.rabbitdlq.config.RabbitConfig.TTL;

@Service
public class OrderService {
    @Autowired
    private OrderRepository orderRepository;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    //创建订单
    @Transactional
    public Order add(Order order) {
        //初始化状态
        order.setStatus(OrderStatus.init.name());
        Order o = orderRepository.save(order);
        //放入redis 设置超时
        redisTemplate.opsForValue().set(OrderHelper.key(String.valueOf(o.getId())), JSON.toJSONString(o), Duration.ofMillis(TTL));
        //放入队列
        rabbitTemplate.convertAndSend(RabbitConfig.EXCHANGE, RabbitConfig.ROUTE_KEY, JSON.toJSONString(o));
        return o;
    }

    @Transactional
    public Order pay(Order order) {
        Order o;
        Object o1 = redisTemplate.opsForValue().get(OrderHelper.key(String.valueOf(order.getId())));
        //redis不为空的话去付款
        if (Objects.nonNull(o1)) {
            order.setStatus(OrderStatus.success.name());
            o = orderRepository.save(order);
        } else {
            //为空的话设置成查看数据库状态返回
            o = orderRepository.findById(order.getId()).orElseThrow(() -> new RuntimeException(String.format("id:%s not found", order.getId())));
        }
        return o;
    }
}
